﻿using Grpc.Core;
using GrpcCommon.Helpers;
using GrpcCommon.Models;
using GrpcExample;
using Newtonsoft.Json;

namespace GrpcServer.Services
{
    public class ExampleService : ExampleServer.ExampleServerBase
    {
        private readonly ILogger<ExampleService> _logger;

        public ExampleService(ILogger<ExampleService> logger)
        {
            _logger = logger;
        }

        public override Task<ExampleResponse> UnaryCall(ExampleRequest request, ServerCallContext context)
        {
            Console.WriteLine(request.ToString());
            _logger.LogInformation(request.ToString());
            var tokenRes = JwtHelper.ValidateJwt(request.Token, request.SecurityKey);

            // 正常响应客户端一次
            ExampleResponse result;

            if (tokenRes.Item1)
            {
                var payLoad = JsonConvert.DeserializeObject<JwtToken>(tokenRes.Item2);
                if (payLoad == null)
                {
                    result = new ExampleResponse
                    {
                        Code = -1,
                        Result = false,
                        Message = "payLoad为空"
                    };
                }
                else
                {
                    if (!request.UserId.Equals(payLoad.UserId))
                    {
                        result = new ExampleResponse
                        {
                            Code = -1,
                            Result = false,
                            Message = "userid不匹配"
                        };
                    }
                    else
                    {
                        var userDetail = JsonConvert.DeserializeObject<UserDetails>(request.UserDetail.Fields.ToString());
                        result = new ExampleResponse
                        {
                            Code = 200,
                            Result = true,
                            Message = $"UnaryCall 单次响应: {request.UserId},{userDetail?.UserName}"
                        };
                    }
                }
            }
            else
            {
                // 正常响应客户端一次
                result = new ExampleResponse
                {
                    Code = -1,
                    Result = false,
                    Message = tokenRes.Item2
                };
            }
            return Task.FromResult(result);
        }

        public override async Task StreamingFromServer(ExampleRequest request, IServerStreamWriter<ExampleResponse> responseStream, ServerCallContext context)
        {
            // 无限响应客户端
            while (!context.CancellationToken.IsCancellationRequested)
            {
                await responseStream.WriteAsync(new ExampleResponse
                {
                    Code = 200,
                    Result = true,
                    Message = $"StreamingFromServer 无限响应: {Guid.NewGuid()}"
                });
                await Task.Delay(TimeSpan.FromSeconds(3), context.CancellationToken);
            }
        }

        public override async Task<ExampleResponse> StreamingFromClient(IAsyncStreamReader<ExampleRequest> requestStream, ServerCallContext context)
        {
            // 处理请求
            await foreach (var req in requestStream.ReadAllAsync())
            {
                Console.WriteLine(req.UserId);
            }

            // 响应客户端
            return new ExampleResponse
            {
                Code = 200,
                Result = true,
                Message = $"StreamingFromClient 单次响应: {Guid.NewGuid()}"
            };
        }

        public override async Task StreamingBothWays(IAsyncStreamReader<ExampleRequest> requestStream, IServerStreamWriter<ExampleResponse> responseStream, ServerCallContext context)
        {
            // 服务器响应客户端一次
            // 处理请求
            //await foreach (var req in requestStream.ReadAllAsync())
            //{
            //    Console.WriteLine(req.UserName);
            //}

            // 请求处理完成之后只响应一次
            //await responseStream.WriteAsync(new ExampleResponse
            //{
            //    Code = 200,
            //    Result = true,
            //    Message = $"StreamingBothWays 单次响应: {Guid.NewGuid()}"
            //});
            //await Task.Delay(TimeSpan.FromSeconds(3), context.CancellationToken);

            // 服务器响应客户端多次
            // 处理请求
            var readTask = Task.Run(async () =>
            {
                await foreach (var req in requestStream.ReadAllAsync())
                {
                    Console.WriteLine(req.UserId);
                }
            });

            // 请求未处理完之前一直响应
            while (!readTask.IsCompleted)
            {
                await responseStream.WriteAsync(new ExampleResponse
                {
                    Code = 200,
                    Result = true,
                    Message = $"StreamingBothWays 请求处理完之前的响应: {Guid.NewGuid()}"
                });
                await Task.Delay(TimeSpan.FromSeconds(3), context.CancellationToken);
            }

            // 也可以无限响应客户端
            //while (!context.CancellationToken.IsCancellationRequested)
            //{
            //    await responseStream.WriteAsync(new ExampleResponse
            //    {
            //        Code = 200,
            //        Result = true,
            //        Message = $"StreamingFromServer 无限响应: {Guid.NewGuid()}"
            //    });
            //    await Task.Delay(TimeSpan.FromSeconds(3), context.CancellationToken);
            //}
        }
    }
}
